const router = require('koa-router')()
const upload = require('../middleware/upload')
const { StateModel, TypeModel, GradesModel } = require('../db/yan')
const { MessageModel } = require('../db/pan')
const jwt = require('jsonwebtoken')
router.prefix('/yan')

async function all(item, Rge) {
    let a = new RegExp(Rge, 'i')
    let b = await TypeModel.findOne({ id: item })
    let obj = await StateModel.find({ $and: [{ progress_id: b._id }, { address: a }] }).sort({ 'level': -1 }).populate('processor_id').populate('department').populate('repair_id').populate('progress_id').populate('grade_id')
    return obj
}

router.get('/', function (ctx, next) {
    ctx.body = '闫鸿'
})

router.post('/work_sheet', async (ctx, next) => {
    let data = ctx.request.body
    let { loginid } = jwt.verify(ctx.request.header.authorization.split(' ')[1], 'flag')
    let dan = await TypeModel.findOne({ id: 1 })
    let obj = await StateModel.create({ repair_id: loginid, progress_id: dan._id, ...data })
    await MessageModel.create({
        title: "这是一个需要时间计算的消息标题",
        order: obj._id
    })
    let code = ''
    if (obj) {
        code = "创建成功"
    } else {
        code = "创建失败"
    }
    ctx.body = {
        code
    }
})

router.get('/data', async (ctx, next) => {
    let obj = []
    let Rge = ctx.query.search
    switch (ctx.query.id * 1) {
        case 1:
            obj = await all(1, Rge)
            break
        case 2:
            obj = await all(2, Rge)
            break
        case 3:
            obj = await all(3, Rge)
            break
        case 4:
            obj = await all(4, Rge)
            break
        default:
            obj = '错误'
            break;
    }
    ctx.body = {
        data: obj
    }
})


router.get('/work_dan', async (ctx, next) => {
    try {
        let id = ctx.query.id
        let obj = await StateModel.findOne({ _id: id }).populate('processor_id').populate('department').populate('repair_id').populate('progress_id').populate('grade_id')
        ctx.body = {
            data: obj
        }
    } catch (err) {
        ctx.body = {
            data: err
        }
    }

})

router.put('/work_update', async (ctx, next) => {
    try {
        let id = ctx.query.id
        let num = ctx.query.num * 1
        let { loginid } = jwt.verify(ctx.request.header.authorization.split(' ')[1], 'flag')
        let progress_id = await TypeModel.findOne({ id: num })
        console.log(ctx.request.body);
        await StateModel.updateOne({ _id: id }, { $set: { processor_id: loginid, progress_id: progress_id, ...ctx.request.body } })
        ctx.body = {
            data: '修改成功'
        }
    } catch (err) {
        ctx.body = {
            data: `修改失败 原因${err}`
        }
    }

})

router.get('/type', async (ctx, next) => {
    let data = await TypeModel.aggregate([
        {
            $lookup: {
                from: 'state',
                localField: '_id',
                foreignField: 'progress_id',
                as: 'children',
            }
        },
        {
            $sort: { 'level': -1 }
        }
    ])

    ctx.body = { data }
})



//上传图片
router.post('/head', upload.single('file'), async (ctx, next) => {
    // 图片地址拼接
    const headPath = 'http://localhost:3000/uploads/' + ctx.req.file.filename
    ctx.body = {
        code: 1,
        filename: headPath// 返回图片地址
    }
})

router.post('/grades', async (ctx, next) => {
    const obj = await GradesModel.create({ ...ctx.request.body })
    try {
        const id = ctx.query.id
        let a = await StateModel.updateOne({ _id: id }, { grade_id: obj._id })
        console.log(a);
        let code = ''
        if (obj) {
            code = "创建成功"
        } else {
            code = "创建失败"
        }
        ctx.body = {
            code
        }
    } catch (err) {
        ctx.body = {
            code: `${err}`
        }
    }

})


module.exports = router 